<template>
  <a-layout>
    <a-layout-header class="header">
      <img src="/logo.png" alt="lang" style="float: left; width: 10%; height: 5%;">
      <h1 style="color: white;">Document Upload</h1>
    </a-layout-header>
    <a-layout-content class="content" style="padding: 20px;">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-input
            v-model:value="question"
            placeholder="Enter your question"
            style="margin-bottom: 20px;"
          />
          <a-button type="primary" @click="askQuestion">Ask</a-button>
          <div v-if="response" class="response-box">
            <p>{{ response }}</p>
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="16" style="margin-top: 20px;">
        <a-col :span="24">
          <a-upload
            :before-upload="beforeUpload"
            :show-upload-list="false"
            ref="upload"
            accept=".pdf,.doc,.docx"
            multiple
          >
            <template #default>
              <a-button type="primary" @click="triggerUpload">Select File</a-button>
            </template>
          </a-upload>
        </a-col>
      </a-row>
      <a-row :gutter="16" style="margin-top: 20px;">
        <a-col :span="24">
          <a-table :data-source="fileList" :columns="columns" row-key="index">
            <template #bodyCell="{ text, record, column }">
              <span v-if="column.key === 'action'">
                <a-button type="link" @click="uploadFile(record.index)">Upload</a-button>
                <a-button type="link" @click="removeFile(record.index)">Delete</a-button>
              </span>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { Layout, Upload, Button, Row, Col, message, Table, Input } from 'ant-design-vue';
import { uploadDocument as uploadDocumentApi, ask as askApi } from '@/api/rag-api';

export default defineComponent({
  components: {
    'a-layout': Layout,
    'a-layout-header': Layout.Header,
    'a-layout-content': Layout.Content,
    'a-upload': Upload,
    'a-button': Button,
    'a-row': Row,
    'a-col': Col,
    'a-table': Table,
    'a-input': Input
  },
  data() {
    return {
      question: '', // 问题输入框的内容
      response: '', // ask 接口的返回内容
      fileList: [] as Array<{ index: number, name: string, type: string, file: File }>, // 文件列表
      columns: [
        { title: '序号', dataIndex: 'index', key: 'index' },
        { title: '文件名称', dataIndex: 'name', key: 'name' },
        { title: '文件类型', dataIndex: 'type', key: 'type' },
        { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } }
      ]
    };
  },
  methods: {
    beforeUpload(file: File) {
      const isAcceptedFormat = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type);
      const isLt10M = file.size / 1024 / 1024 < 10; // 判断文件大小是否小于 10MB

      if (!isAcceptedFormat) {
        message.error('You can only upload PDF or Word documents!'); // 只能上传 PDF 或 Word 文件
        return false;
      }

      if (!isLt10M) {
        message.error('Document must be smaller than 10MB!'); // 文件必须小于 10MB
        return false;
      }

      this.addFileToList(file);
      return false; // 阻止自动上传
    },
    triggerUpload() {
      const uploadElement = this.$refs.upload as HTMLElement;
      uploadElement.click(); // 触发上传
    },
    addFileToList(file: File) {
      const index = this.fileList.length + 1;
      this.fileList.push({
        index,
        name: file.name,
        type: file.type,
        file: file
      });
    },
    async uploadFile(index: number) {
      const record = this.fileList.find(file => file.index === index);
      if (!record) {
        message.error('Please select a document first!'); // 请先选择文件
        return;
      }
      try {
        await uploadDocumentApi(record.file); // 调用 API 上传文件
        message.success('Document uploaded successfully!'); // 文件上传成功
      } catch (error) {
        if (error instanceof Error) {
          message.error(error.message); // 显示错误信息
        } else {
          message.error('An unknown error occurred.'); // 未知错误
        }
      }
    },
    removeFile(index: number) {
      this.fileList = this.fileList.filter(file => file.index !== index);
    },
    askQuestion() {
      if (!this.question) {
        message.error('Please enter a question first!'); // 请先输入问题
        return;
      }

      this.response = ''; // 清空之前的响应内容

      const eventSource = askApi(this.question, (data: string) => {
        this.response += data; // 追加流式输出的数据
      });

      eventSource.onerror = () => {
        message.error('An error occurred while receiving the stream.'); // 显示错误信息
        eventSource.close();
      };
    }
  }
});
</script>

<style>
.header {
  background-color: lightblue;
  text-align: center;
  padding: 10px 0;
}
.content {
  padding: 20px;
}
.response-box {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background-color: #f5f5f5;
}
</style>